<?php

namespace addons\shopro\controller;

use addons\shopro\model\Cart as CartModel;
use think\Db;

class Cart extends Base
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function index()
    {
        $data = CartModel::info();
        $this->success('我的购物车', $data);
    }

    public function add()
    {
        $params = $this->request->post();
        
        // 表单验证
        $this->shoproValidate($params, get_class(), 'add');

        $goodsList = $params['goods_list'];
        $this->success('已添加', CartModel::add($goodsList));
    }

    public function edit()
    {
        $params = $this->request->post();

        // 表单验证
        $this->shoproValidate($params, get_class(), 'edit');

        $this->success('', CartModel::edit($params));
    }

    public function edit2()
    {
        $params = $this->request->post();
        $user = $this->auth->getUser();
        $user_id=$user->id;
        if(empty($user_id))$this->error('请登录');

        $cart=CartModel::
            where('user_id',$user_id)
            ->where('goods_id',$params['id'])
            ->where('sku_price_id',$params['sku'])
            ->find();

        if($params['num']<=0){
            $res=CartModel::where('id',$cart['id'])->delete();
        }else{
            if(empty($cart)){
                $insData=array();
                $insData['user_id']=$user_id;
                $insData['goods_id']=$params['id'];
                $insData['goods_num']=$params['num'];
                $insData['sku_price_id']=$params['sku'];
                $insData['createtime']=time();
                $insData['updatetime']=time();
                $res=CartModel::insert($insData);

            }else{
                $insData=array();
                $insData['goods_num']=$params['num'];
                $insData['updatetime']=time();
                $res=CartModel::where('id',$cart['id'])->update($insData);
            }
        }


        $this->success('成功');
    }

}